import { connection } from '../app/database/mysql'
import { FileModel } from './file.model'
import path from 'path'

export const createFile = async (file: FileModel) => {
  const statement = `INSERT INTO file SET ?`
  const [data] = await connection.promise().query(statement, [file])
  return data
}

export const findFileById = async (fileId: number) => {
  const statement = `SELECT * FROM file WHERE id = ?`
  const [data] = await connection.promise().query(statement, [fileId])
  return data[0]
}

export const imageResizer = async (image: any, file: Express.Multer.File) => {
  const { width } = image
  const filePath = path.join(file.destination, 'resized', file.filename)
  const fileExt = file.mimetype.split('/')[1]

  const autoHeight = (width: number) => width * (9 / 16)

  const sizes = [1280, 640, 320]

  for (let size of sizes) {
    if (width >= size) {
      image
        .resize({ w: size, h: autoHeight(size) })
        .write(
          `${filePath}-${
            size === 640 ? 'medium' : size === 320 ? 'small' : 'large'
          }.${fileExt}`,
          { quality: 80 }
        )
    }
  }
}
